#-*-coding=utf8-*-
import numpy as np 
import os
from GeneralKit import *
from blueAPI import blueAPI
#import msvcrt
import threading

def dataProcess(datalist):
	data = [0.0, 0.0, 0.0]
	for i in range(len(datalist)):
		if datalist[i] >= 0.00 and datalist[i] < 45.00:
			data[i] = 0
		elif datalist[i] >= 45.00 and datalist[i] < 90.00:
			data[i] = 1
		elif datalist[i] < 0.00 and datalist[i] >= -45.00:
			data[i] = 2
		elif datalist[i] < -45.00 and datalist[i] >= -90.00:
			data[i] = 3
	return data


def dyncollect(blueObj, gest, index):
	#在此修改默认保存的文件夹，请以 / 结尾
	defaultSavingDir = "./blue_data/"
	if not os.path.exists(defaultSavingDir):
		os.mkdir(defaultSavingDir)

	#blue = blueAPI()
	#blue.connect()
	#gestDict = get_dict()
	blue = blueObj

	#gestDict = {}
	#for i in range(138):
	#	gestDict[i] = '测试'

	#initial
	datas = []
	res = []
	count = 0
	flags = [False, False]

	print("动态数据收集开始")
	'''
	gest = input("请输入当前要收集的手势的编号（1-137）\n")
	while not gest.isdigit() or int(gest)>137 or int(gest)<1:
		gest = input("请输入当前要收集的手势的编号（1-137）\n")
	print("你要收集的手势为"+gestDict[int(gest)])
	index = int(input("请确认本次采样的索引（0-×××）\n"))

	gestFlag = input('输入s开始收集，按q退出')
	'''
	while(1):
		gestFlag = '0'
		t = threading.Thread(target=stop, args=(flags,1,))
		t.start()
		flags[0] = True
		print("[INFO] 数据收集中...")
		while(flags[0] == True):
			data = dataProcess(blue.getData())
			temple = tuple(data)
			#time.sleep(0.01)
			res.append(temple)
		for x in range(len(res)):
			if x == int((len(res) / 12) * count):
				print(count, x)
				datas.append(res[x])
				count += 1
		dst = np.array(datas)
		if len(datas) >= 12:
			np.savetxt(defaultSavingDir + gest + "_" + str(index) + ".txt", dst)
			print("[INFO] 手势数据收集完成！")
		else:
			print("[INFO] 数据长度不足,无效收集！")
		break
	return True

if __name__ == '__main__':
	dyncollect()
